<?php

namespace app\model\goods;

use app\base\BaseModel;

/**
 * 模型-GoodsTypeModel
 * Class GoodsTypeModel
 * @package app\model
 */
class GoodsAttributeModel extends BaseModel
{
    protected $name = 'goods_attribute';

    /**
     * 获取属性值数组数据
     * @param string $goods_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAttrList($goods_id = '')
    {
        $attr_list_arr = [];
        if (empty($goods_id)) {
            return $attr_list_arr;
        }
        $map = ['goods_id' => $goods_id];
        $attr_list = $this->where($map)->select();
        $attr_v_model = new GoodsAttributeValueModel();
        if (!empty($attr_list)) {
            foreach ($attr_list as $value) {
                $list = $attr_v_model->getListArr($value['id']);
                $attr_list_arr[] = [
                    'id' => $value['id'],
                    'name' => $value['name'],
                    'list' => $list
                ];
            }
        }
        return $attr_list_arr;
    }

    /**
     * 刷新
     * @param $goods_id
     * @param $attr_ids
     * @return bool
     */
    public static function upAttrGoodsId($goods_id, $attr_ids)
    {
        $ret = self::whereIn('id', $attr_ids)->update(['goods_id' => $goods_id]);
        $model = new GoodsAttributeValueModel();
        $model->whereIn('attribute_id', $attr_ids)->update(['goods_id' => $goods_id]);
        if ($ret === false) {

            return false;
        }
        return true;
    }

    /**
     * 删除属性
     * @param string $id
     * @return bool
     * @throws \Exception
     */
    public static function delAttr($id = '')
    {
        if (empty($id)) {
            return false;
        }
        if (is_array($id)) {
            self::whereIn('id', $id)->delete();
            $attr_v_model = new GoodsAttributeValueModel();
            $attr_v_model->whereIn('attribute_id', $id)->delete();
        } else {
            self::where(['id' => $id])->delete();
            $attr_v_model = new GoodsAttributeValueModel();
            $attr_v_model->where('attribute_id', $id)->delete();
        }
        return true;
    }

    /**
     * 清除无用的规格
     * @return bool
     * @throws \Exception
     */
    public static function clearGoodsAttr()
    {
        $map = [
            'goods_id' => 0
        ];
        self::where($map)->delete();
        $attr_v_model = new GoodsAttributeValueModel();
        $attr_v_model->where($map)->delete();
        return true;
    }
}
